//
//  TTPresentViewController.swift
//  WeiBo
//
//  Created by 涂永江 on 2017/6/5.
//  Copyright © 2017年 涂永江. All rights reserved.
//

import UIKit
import SVProgressHUD

private let client_id = 964998189
private let redirect_uri = "http://www.itcast.cn"
class TTPresentViewController: UIViewController {

    var webView:UIWebView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title1: "注销", target: self, action: #selector(zhuxiao), imageName: nil)
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title1: "自动填充", target: self, action: #selector(jumto), imageName: nil)
        
       let request  = URLRequest(url: URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)")!)
        
         webView?.loadRequest(request)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func loadView() {
        
        webView = UIWebView()
        webView?.delegate = self as UIWebViewDelegate
        view = webView
        
    }
    //注销
    func zhuxiao()
    {
    self.dismiss(animated: true, completion: nil)
    }
    
    //密码填充
    func jumto()
    {
    
     webView?.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value='15827525622';document.getElementById('passwd').value='13487011629';")
  
    }
    
  
}
extension TTPresentViewController:UIWebViewDelegate{
    
    //开始加载数据
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    //完成加载数据
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载数据出现错误
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    //将要开始加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request.url?.absoluteString)
        if request.url?.absoluteString.hasPrefix(redirect_uri) == true
        {
         
             //query是拿到url ?号后面的参数的
            if let query = request.url?.query, query.hasPrefix("code=")
            {
               //截取=号后面的授权码
               let code = query.substring(from: "code=".endIndex)
                
                TTHMUserAccountViewModel.sharedAccountModel.requestToken(code: code, isScuess: { (issuccess) in
                    
                    if issuccess == true
                    {
                    
                        self.dismiss(animated: true, completion: { 
                            //进入欢迎页面
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: SwitchRootVCNotificationName), object: self)
                            
                        })
                        
                             print("成功")
                    
                    }else
                    {
                    
                           print("失败")
                    }
                })
            }else{
       
                print("取消授权")
         
       self.dismiss(animated: true, completion: nil)
            }
            return false
        }
        return true
    }
    

    
}
    
